//
//  DALoginViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/25.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DALoginViewController.h"
#import "Utility.h"
#import "DADataHandel.h"
#import "DAUserProfile.h"
#import "DAAlertView.h"
#import "GDataXMLNode.h"
#import "DAButton.h"
//#import "MBProgressHUD.h"
#import "SVProgressHUD.h"
#import "DALoginModel.h"
#import "DAHeader.h"
#import "AFNetworking.h"
#import "DAloginPersonalInformation.h"
#import "DALocalMessageSingletonModel.h"
#import "JPUSHService.h"

typedef void(^NetWorkStatus)(id result);

@interface DALoginViewController ()<UITextFieldDelegate, NSXMLParserDelegate>
/** LogoImage */
@property (weak, nonatomic) IBOutlet UIImageView *DALogo;
/** 用户名输入框 */
@property (weak, nonatomic) IBOutlet UITextField *UserNameTextField;
/** 密码输入框 */
@property (weak, nonatomic) IBOutlet UITextField *PassWordTextField;
/** 登录按钮 */
@property (weak, nonatomic) IBOutlet DAButton *loginButton;
/** 存储数据的数组 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** MBProgressHud */
//@property (nonatomic,strong) MBProgressHUD *hud;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *LogoToTop;
@property (nonatomic, strong) DAAlertView *alertView;

@property (nonatomic, copy) NSString *userID;

@end

@implementation DALoginViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.UserNameTextField becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    /** 调用颜色设置 */
    [self configureViewStyle];
    /** 调用输入框的设置*/
    [self inputUserNameAndPassword];
    /** 调用根据设备 更改约束的方法*/
    [self dependOnBoundsUpdateLogoConstraint];
}
#pragma mark - 根据设备 更改约束
- (void)dependOnBoundsUpdateLogoConstraint{
    if (self.view.bounds.size.width >=  375) {
        self.LogoToTop.constant = 100;
    }else{
        self.LogoToTop.constant = 50;
    }
}
#pragma mark - 颜色设置
- (void)configureViewStyle{
    self.view.backgroundColor = [UIColor supportGreenColor];
    /** 登录按钮的设置 */
    self.loginButton.buttonAlignment = DAButtonAlignmentImageCenter;
    [self.loginButton.layer setCornerRadius:30];
    [self.loginButton setBackgroundColor:[UIColor supportGreenColor]];
    [self.loginButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    [self.loginButton.layer setBorderWidth:1];
    [self.loginButton setImage:[UIImage imageNamed:@"arrow"] forState:UIControlStateNormal];
    [self.loginButton setTintColor:[UIColor whiteColor]];
    /** 用户名输入框和密码输入框的背景颜色 */
    self.UserNameTextField.backgroundColor = [UIColor whiteColor];
    self.PassWordTextField.backgroundColor = [UIColor whiteColor];
    self.UserNameTextField.returnKeyType = UIReturnKeyDone;
    self.PassWordTextField.returnKeyType = UIReturnKeyDone;
    self.UserNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.PassWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.UserNameTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.UserNameTextField.placeholder = NSLocalizedString(@"USERNAME", nil);
    self.PassWordTextField.placeholder = NSLocalizedString(@"PASSWORD", nil);
}
#pragma mark - 点击键盘的next
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.tag == 1001) {
        /** 点击了用户名的输入框*/
        [self.PassWordTextField becomeFirstResponder];
    }else{
        /** 点击了密码输入框*/
        [self onTouchLogin:nil];
        [self.PassWordTextField resignFirstResponder];
    }
    return YES;
}
#pragma mark - 用户名和密码输入设置
- (void)inputUserNameAndPassword{
    self.UserNameTextField.delegate = self;
    self.UserNameTextField.keyboardType = UIKeyboardTypeASCIICapable;
    self.PassWordTextField.delegate = self;
    self.PassWordTextField.secureTextEntry = YES;
    self.UserNameTextField.tag = 1001;
    self.PassWordTextField.tag = 1002;
}
#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField.tag == 1001) {
        self.DALogo.image = [UIImage imageNamed:@"puppy@3x"];
    }else if(textField.tag == 1002) {
        self.DALogo.image = [UIImage imageNamed:@"puppy2@3x"];
    }
    return YES;
}
#pragma mark - 给login按钮添加手势
- (IBAction)onTouchLogin:(id)sender {
    NSLog(@"登录");
    [self.UserNameTextField resignFirstResponder];
    [self.PassWordTextField resignFirstResponder];
    NSString *userNameIsEmpty = NSLocalizedString(@"userNameIsEmpty", nil);
    NSString *pleaseReenter = NSLocalizedString(@"pleaseReenter", nil);
    NSString *hint = NSLocalizedString(@"hint", nil);
    if (self.UserNameTextField.text.length == 0) {
        /**  弹出框 当点击登录按钮 用户名为空的时候 */
        [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:hint contentText:userNameIsEmpty cancelButtonTitle:pleaseReenter buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {
            if (index == 999) {
                [self.UserNameTextField becomeFirstResponder];
            }
        }];
    }
    else if (self.PassWordTextField.text.length == 0) {
         NSString *passWordIsEmpty = NSLocalizedString(@"passWordIsEmpty", nil);
        /**  弹出框 当点击登录按钮 用户名不为空 密码为空的时候 */
        [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:hint contentText:passWordIsEmpty cancelButtonTitle:pleaseReenter buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {
            if (index == 999) {
                [self.PassWordTextField becomeFirstResponder];
            }
        }];
    }
    else{
    /** 调用网络请求 */
     [self prepareData];
    }
}
#pragma mark - 数据请求
- (void)prepareData{
    /** 调用菊花 */
    [self loadMBProgress];
    NSString *url = DALoginURL;
    NSString *userName = self.UserNameTextField.text;
    NSString *passWord = self.PassWordTextField.text;
    NSDictionary *dic = @{@"userName":userName,@"passWord":passWord};
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if([result[@"result"] isKindOfClass:[NSDictionary class]]){
        NSString *isSuccessful = result[@"result"][@"login"];
        if ([isSuccessful isEqualToString:@"true"]) {
            DAloginPersonalInformation *personalInformation = [[DAloginPersonalInformation alloc]init];
            [personalInformation dataTransformModelWith:result[@"result"]];
            self.userID = result[@"result"][@"userID"];
            /** 移除菊花 */
            //[self.hud removeFromSuperview];
            [SVProgressHUD dismiss];
            /** 调用登录成功方法 */
            [self isLoginSuccessful];
            /** 保存登录状态 */
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setBool:YES forKey:@"isLogin"];
            
            //保存账号
            [userDefaults setObject:self.UserNameTextField.text forKey:@"UserAccount"];
        }
//        else if([result isEqualToString:@"请求服务器超时"]) {
//            /** 没有数据 登录失败 */
//            [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:@"提示" contentText:@"请求服务器超时" cancelButtonTitle:@"重新登录 " buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {
//                if (index == 999) {
//                    self.DALogo.image = [UIImage imageNamed:@"puppy@3x"];
//                    [self prepareData];
//                }
//                /** 移除菊花 */
//                [self.hud removeFromSuperview];
//                
//            }];
       // }
        
        else{
                /** 没有数据 登录失败 */
            NSString *userNamePassWordError = NSLocalizedString(@"userNamePassWordError", nil);
            NSString *pleaseReenter = NSLocalizedString(@"pleaseReenter", nil);
                [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:@"提示" contentText:userNamePassWordError cancelButtonTitle:pleaseReenter  buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {
                    if (index == 999) {
                        self.UserNameTextField.text = nil;
                        self.PassWordTextField.text = nil;
                        self.DALogo.image = [UIImage imageNamed:@"puppy@3x"];
                        [self.UserNameTextField becomeFirstResponder];
                    }
                    /** 移除菊花 */
                    //[self.hud removeFromSuperview];
                }];
        }
        }else{
            NSString *isLoginFailed = NSLocalizedString(@"isLoginFailed", nil);
            NSString *pleaseReenter = NSLocalizedString(@"pleaseReenter", nil);
            [DAAlertView showDAAlertWithPositionType:DAAlertDisplayerPositionTypeCenter animationType:DAAlertDisplayerShowTypeBounce titleText:@"提示" contentText:isLoginFailed cancelButtonTitle:pleaseReenter buttonList:nil handleActionBlock:^(DAAlertView *displayer, NSInteger index) {
                if (index == 999) {
                    self.UserNameTextField.text = nil;
                    self.PassWordTextField.text = nil;
                    self.DALogo.image = [UIImage imageNamed:@"puppy@3x"];
                    [self.UserNameTextField becomeFirstResponder];
                }
                /** 移除菊花 */
                //[self.hud removeFromSuperview];
            }];
        }
        [SVProgressHUD dismiss];
    }];
}
//#pragma mark - 获取个人信息
//- (void)personalData{
//    /** 个人信息URL*/
//   // NSString *url = PersonalInformationURL;
//    /** 从本地获取到cookie*/
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSData *data =  [defaults objectForKey:@"sessionCookies"];
//  [DADataHandel getURL:url parame:data result:^(id result) {
//      if (result) {
//          DAUserProfile *user = [[DAUserProfile alloc]init];
//           [user dataTransformModelWith: result[@"document"]];
//      }else{
//          /** 没有获取到个人信息数据 */
//          NSLog(@"没有获取到个人信息");
//      }
//  }];
//}
#pragma mark - 登录成功
- (void)isLoginSuccessful{
    [UIView animateWithDuration:0.5 animations:^{
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        self.view.window.rootViewController = main.instantiateInitialViewController;
        [self CreatDALocalMessage];
        NSLog(@"%@", self.userID);
        [JPUSHService setAlias:self.userID callbackSelector:nil object:nil];
      //  [JPUSHService setTags:<#(NSSet *)#> alias:<#(NSString *)#> callbackSelector:<#(SEL)#> object:<#(id)#>
        
    }];
}



#pragma mark - 修改状态栏的颜色
- (UIStatusBarStyle)preferredStatusBarStyle{
  return UIStatusBarStyleLightContent;
}
#pragma mark - 加载菊花
- (void)loadMBProgress{
    NSString *isLogin = NSLocalizedString(@"isLogin", nil);
    [SVProgressHUD showWithStatus:isLogin];
//    self.hud = [[MBProgressHUD alloc]initWithView:self.view];
//    self.hud.dimBackground = NO;
//    /** 设置加载文字 */
//    self.hud.labelText = @"登录中..";
//    self.hud.minShowTime = 20;
//    self.hud.activityIndicatorColor = [UIColor themeWhiteColor];
//    self.hud.labelColor = [UIColor themeWhiteColor];
//    [self.view addSubview:self.hud];
//    [self.hud showAnimated:NO whileExecutingBlock:^{
//    } completionBlock:^{
//        [self.hud removeFromSuperview];
//        self.hud = nil;
//    }];
}
#pragma mark - 点击空白 键盘消失
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.UserNameTextField resignFirstResponder];
    [self.PassWordTextField resignFirstResponder];
}

#pragma mark - AFN网络状态判断
+ (void)networkReachabilityStatus:(NetWorkStatus)block{
    /** 网络连接检测封装*/
    AFNetworkReachabilityManager *reachManeger = [AFNetworkReachabilityManager sharedManager];
    /** 开始检测*/
    [reachManeger  startMonitoring];
    [reachManeger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                block(@0);
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                block(@1);
            case AFNetworkReachabilityStatusReachableViaWiFi:
                block(@2);
            case AFNetworkReachabilityStatusUnknown:
                block(@(-1));
            default:
                break;
        }
        
    }];
}

#pragma mark - 初始化DALocalMessageSingletonModel
- (void)CreatDALocalMessage{
  DALocalMessageSingletonModel *model = [DALocalMessageSingletonModel sharedDALocalMessageSingletonModel];
  //[model prepareDataWithUserID:self.userID];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"0" forKey:@"lastReplyID"];
    [model prepareDataWithUserID:self.userID lastReplyID:nil pageNumber:@"0"  block:^(BOOL isSuccessful) {
        if (isSuccessful) {
            NSLog(@"登录成功 更新消息数据成功");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationUpData" object:nil];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
